﻿using System.Collections.Generic;
using UnityEngine;
using GameProtocols;
using System;
using Framework;

public class LogicEntity
{
    [HideInInspector]
    public int EntityID;
    public long PlayerID;

    public ObjHandle<LogicEntity> self = ObjHandle<LogicEntity>.NULL;
    [HideInInspector]
    public int characterID;

    List<LogicComponent> components = new List<LogicComponent>();

    public Action<LogicEntity> onCollide;

    public virtual void Destroy()
    {
        for (int i = 0; i < components.Count; i++)
        {
            components[i].Destroy();
        }
    }

    public T GetLogicComponent<T>() where T : class
    {
        for (int i = 0; i < components.Count; i++)
        {
            if (components[i] is T)
                return (T)components[i];
        }

        return null;
    }

    public void AddLogicComponent(LogicComponent component)
    {
        components.Add(component);
    }

    public void FixedUpdate()
    {
        for (int i = 0; i < components.Count; i++)
        {
            components[i].DoUpdate(LockstepEngine.FrameDeltaTime);
        }
    }

    public void Init()
    {
        for (int i = 0; i < components.Count; i++)
        {
            components[i].Init(this);
        }

        for (int i = 0; i < components.Count; i++)
        {
            components[i].Start();
        }
    }

    public void SendEntityMessage(int opcode, params object[] content)
    {
        VisualEntityManager.Instance.SendMsg(EntityID, opcode, content);
    }
}
